<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">

      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <!--        <a-button type="primary" icon="printer" @click="openPrintPreview">打印预览</a-button>-->
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code"  placeholder="请输入单据编号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="出库类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outboundType">
              <j-dict-select-tag type="list" v-model="model.outboundType" dictCode="ck_type" placeholder="请选择出库类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseId">
              <j-search-select-tag v-model="model.warehouseId" dict="erp_warehouse,name,id" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="上级单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="superiorOrderNumber">
              <a-input v-model="model.superiorOrderNumber" placeholder="请输入上级单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="出库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outboundDate">
              <j-date placeholder="请选择出库日期" v-model="model.outboundDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierId">
              <j-search-select-tag v-model="model.supplierId" dict="erp_supplier,name,id" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cutomerName">
              <a-input v-model="model.cutomerName" placeholder="请输入客户名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="部门车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departmentWorkshop">
              <j-search-select-tag v-model="model.departmentWorkshop" dict="sys_depart,depart_name,id" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date placeholder="请选择创建日期" v-model="model.createTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注" ></a-input>
            </a-form-model-item>
          </a-col>

        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="出库单信息" :key="refKeys[0]" :forceRender="true">
        <div class="table-operator">
          <a-button @click="handleAddInformations" type="primary" icon="plus">新增</a-button>
        </div>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussOutboundOrderInformationTable.loading"
          :columns="bussOutboundOrderInformationTable.columns"
          :dataSource="bussOutboundOrderInformationTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
        >
          <template v-slot:action="{row}">
            <a @click="deleteRow(row)">删除</a>
          </template>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="库存明细" :key="refKeys[1]" :forceRender="true">
        <a-table
          ref="table"
          size="middle"
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{x:true}"
          :columns="bussOutboundOrderDetailTable.columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :expandedRowKeys="bussOutboundOrderDetailTable.expandedRowKeys"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange"
          @expand="handleExpand"
          v-bind="tableProps">
          <template v-if="record.parent == 0" slot="quantity" slot-scope="text, record">
            <editnumber-cell :text="text" @change="onCellChange(record, 'quantity', $event)" ></editnumber-cell>
          </template>
          <span slot="action" slot-scope="text, record">
<!--          <a v-if="record.parent == 1" @click="handleAddChild(record)">添加明细</a>-->

            <!--          <a-divider type="vertical" />-->
            <a-popconfirm v-if="record.parent == 0"  title="确定删除吗?" @confirm="() => handleDeleteNode(record)" placement="topLeft">
                  <a>删除</a>
            </a-popconfirm>
        </span>

        </a-table>
      </a-tab-pane>
    </a-tabs>
    <buss-inventory-list-modal ref="selectInventory"
                               @inventoryOk="inventoryOk"
                               :category=category
                               :warehouseId=model.warehouseId
                               checkval='checkbox'>
    </buss-inventory-list-modal>
    <buss-inbound-list-modal ref="selectInbound"
                             @inboundOk="inboundOk"
                             :category=inventory
                             checkval='checkbox'>
    </buss-inbound-list-modal>
  </a-spin>
</template>

<script>

import { getAction, postAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue , randomNumber, randomUUID } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import estar from '../../../estar/oa/util/estar'
import BussInventoryListModal from "@comp/base/modal/BussInventoryListModal";
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import EditableCell from '@comp/table/EditableCell'
import EditnumberCell from '@comp/table/EditnumberCell'
import BussInboundListModal from "@comp/base/modal/BussInboundListModal";
import moment from 'dayjs'
import store from '@/store'

export default {
  name: 'BussPackageOutboundOrderManagementForm',
  mixins: [JVxeTableModelMixin , JeecgListMixin],
  components: {
    JFormContainer,
    BussInventoryListModal,
    EditableCell,
    BussInboundListModal,
    EditnumberCell
  },
  data() {
    return {
      procSelectRows: [],
      category: '2',
      inventory: '',
      selectedRowKeys: [],
      selectionRows: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      detailTemp: {},
      model:{
        outboundDate: '',
        createTime: ''
      },
      mainMap: new Map(),
      detailMap: new Map(),
      validatorRules: {
        outboundType: [
          { required: true, message: '请选择出库类型!'},
        ],
        warehouseId: [
          { required: true, message: '请选择仓库!'},
        ],
      },
      dataSource: [],
      refKeys: ['bussOutboundOrderInformation', ],
      tableKeys:['bussOutboundOrderInformation', ],
      activeKey: 'bussOutboundOrderInformation',
      // 出库单信息
      bussOutboundOrderInformationTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编号',
            key: 'materialCode',
            // type: JVXETypes.input,
            width:"120px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '客户物料编号',
            key: 'customerMaterialCode',
            // type: JVXETypes.input,
            width:"120px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '物料名称',
            key: 'materialName',
            // type: JVXETypes.select,
            width:"150px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '规格型号',
            key: 'noneSpec',
            // type: JVXETypes.input,
            width:"80px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '主计量',
            key: 'meUnit',
            type: JVXETypes.select,
            width:"100px",
            dictCode: 'ji_unit',
            disabled: true
          },
          {
            title: '数量',
            key: 'quantity',
            // type: JVXETypes.inputNumber,
            width:"80px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '库存数量',
            key: 'inventoryQuantity',
            // type: JVXETypes.input,
            width:"80px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          // {
          //   title: '占用库存',
          //   key: 'occupyInventory',
          //    // type: JVXETypes.input,
          //   width:"80px",
          //   placeholder: '请输入${title}',
          //   defaultValue:'',
          // },
          {
            title: '可用数量',
            key: 'availableQuantity',
            // type: JVXETypes.input,
            width:"80px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '辅助单位',
            key: 'auUnit',
            // type: JVXETypes.input,
            width:"80px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '辅助数量',
            key: 'auQuantity',
            // type: JVXETypes.input,
            width:"80px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '辅助库存数量',
            key: 'auInQuantity',
            // type: JVXETypes.input,
            width:"120px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '占用辅助库存',
            key: 'occupyAuInventory',
            // type: JVXETypes.input,
            width:"120px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '换算率',
            key: 'conversionRate',
            type: JVXETypes.inputNumber,
            width:"80px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width:"120px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          }
        ]
      },
      // 出库单明细
      url: {
        list: "/outbound/bussPackageOutboundOrderDetail/rootList",
        childList: "/outbound/bussPackageOutboundOrderManagement/queryOutboundOrderDetailByMainId",
        getChildListBatch: "/outbound/bussPackageOutboundOrderDetail/getChildListBatch",
        add: "/outbound/bussPackageOutboundOrderManagement/add",
        edit: "/outbound/bussPackageOutboundOrderManagement/edit",
        queryById: "/outbound/bussPackageOutboundOrderManagement/queryById",
        bussOutboundOrderInformation: {
          list: '/outbound/bussPackageOutboundOrderManagement/queryBussOutboundOrderInformationByMainId'
        },
      },
      bussOutboundOrderDetailTable:{
        columns: [
          {
            title:'物料名称',
            align:"left",
            dataIndex: 'materialName',
            width:120,
          },
          {
            title:'物料编号',
            align:"left",
            dataIndex: 'materialCode',
            width:120,
          },
          {
            title:'规格型号',
            align:"left",
            dataIndex: 'noneSpec',
            width:120,
          },
          {
            title:'主计量',
            align:"left",
            dataIndex: 'meUnit_dictText',
            width:70,
          },
          {
            title:'数量',
            align:"left",
            dataIndex: 'quantity',
            scopedSlots: { customRender: 'quantity' },
            width:120,
          },
          {
            title:'批次号',
            align:"left",
            dataIndex: 'batchNumber',
            width:120,
          },
          {
            title:'物料批号',
            align:"left",
            dataIndex: 'materialBatchNumber',
            width:120,
          },
          {
            title:'库位',
            align:"left",
            dataIndex: 'warehouseLocation',
            width:120,
          },
          {
            title:'入库数量',
            align:"left",
            dataIndex: 'inventoryQuantity',
            width:120,
          },
          {
            title:'已出数量',
            align:"left",
            dataIndex: 'outputQuantity',
            width:120,
          },
          {
            title: '可用数量',
            align:"left",
            dataIndex: 'availableQuantity',
            width:120,
          },
          {
            title:'占用数量',
            align:"left",
            dataIndex: 'occupationQuantity',
            width:120,
          },
          {
            title:'入库单号',
            align:"left",
            dataIndex: 'warehousingCode',
            width:120,
          },
          {
            title:'入库日期',
            align:"left",
            dataIndex: 'warehousingDate',
            width:90,
          },
          {
            title:'限用日期',
            align:"left",
            dataIndex: 'restrictedDate',
            width:90,
          },
          {
            title:'供应商',
            align:"left",
            dataIndex: 'supplierName',
            width:150,
          },
          {
            title:'生产车间',
            align:"left",
            dataIndex: 'productionWorkshop_dictText',
            width:120,
          },
          {
            title:'客户名称',
            align:"left",
            dataIndex: 'customerName',
            width:120,
          },
          {
            title:'宝洁供应商编码',
            align:"left",
            dataIndex: 'bjSupplierCode',
            width:120,
          },
          {
            title:'宝洁供应商',
            align:"left",
            dataIndex: 'bjSupplierName',
            width:120,
          },
          {
            title:'宝洁单号',
            align:"left",
            dataIndex: 'bjNo',
            width:120,
          },
          {
            title:'辅助单位',
            align:"left",
            dataIndex: 'auUnit_dictText',
            width:120,
          },
          {
            title:'辅助数量',
            align:"left",
            dataIndex: 'auQuantity',
            width:120,
          },
          {
            title:'入库辅助数量',
            align:"left",
            dataIndex: 'inAuQuantity',
            width:120,
          },
          {
            title:'已出辅助数量',
            align:"left",
            dataIndex: 'outAuQuantity',
            width:120,
          },
          {
            title:'占用辅助数量',
            align:"left",
            dataIndex: 'occupationAuQuantity',
            width:120,
          },
          {
            title:'单位换算率',
            align:"left",
            dataIndex: 'conversionRate',
            width:120,
          },
          {
            title:'备注',
            align:"left",
            dataIndex: 'remark',
            width:120,
          },
          {
            title:'订单编号',
            align:"left",
            dataIndex: 'orderNo',
            width:120,
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/outbound/bussPackageOutboundOrderDetail/rootList",
          childList: "/outbound/bussPackageOutboundOrderDetail/childList",
          getChildListBatch: "/outbound/bussPackageOutboundOrderDetail/getChildListBatch",
          delete: "/outbound/bussPackageOutboundOrderDetail/delete",
          deleteBatch: "/outbound/bussPackageOutboundOrderDetail/deleteBatch",
          exportXlsUrl: "/outbound/bussPackageOutboundOrderDetail/exportXls",
          importExcelUrl: "outbound/bussPackageOutboundOrderDetail/importExcel",
        },
        expandedRowKeys:[],
        hasChildrenField:"hasChild",
        pidField:"pid",
        dictOptions: {},
        loadParent: false,
        superFieldList:[],
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
        }
      }
    }
  },
  created () {
    let time = estar.toDate(new Date(), "yyyy-MM-dd");
    let startTime = estar.toDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    this.model.outboundDate = time;
    this.model.createTime = startTime;
    this.getSuperFieldList();
  },

  methods: {
    handleValueChange({ row, column, value, oldValue }) {
      const field = column.property; // 变更列的字段名

      if(field === 'quantity') {
        var max = parseFloat(row.availableQuantity);
        var num = parseFloat(row.quantity);
        // var zhanyong = 0;
        // if (row.occupyInventory != null){
        //   zhanyong = parseFloat(row.occupyInventory);
        // }
        // var keyong = num - zhanyong;
        if (num > max){
          this.$message.error("输入的数量大于可用数量！")
        }else{
          this.mainMap.set(row.materialId, row.quantity);
        }
      }
    },
    getSequenceNum() {
      let url = "/sys/fillRule/executeRuleByCode/ckd";
      putAction(url, {name: "出库单编码"}).then(res => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result;
        }
      })
    },
    inventoryOk(row){
      let _this = this;
      console.log(row);
      postAction('/inventory/bussInventory/queryByIds', { ids: row , warehouseId:_this.model.warehouseId }).then(res => {
        console.log(res.result)
        let erpGoodsList = res.result;
        erpGoodsList.forEach(function(item,index){
          console.log(item,index)
          let detail = {};
          let details = {};
          // detail.inventoryId = item.id;
          detail.materialId = item.materialId;
          detail.materialCode = item.materialCode;
          detail.materialName = item.materialName;
          detail.noneSpec = item.noneSpec;
          detail.meUnit = item.meUnit;
          // detail.quantity = item.quantity;
          detail.inventoryQuantity = item.quantity;
          detail.availableQuantity = item.availableQuantity;
          console.log(_this.bussOutboundOrderInformationTable.dataSource)
          _this.filterPackageId(item.materialId);
          _this.bussOutboundOrderInformationTable.dataSource.push(detail);
          // details.inventoryId = item.id;
          details.materialId = item.materialId;
          details.materialCode = item.materialCode;
          details.materialName = item.materialName;
          details.id = randomUUID();
          // details.noneSpec = item.noneSpec;
          // details.meUnit = item.meUnit;
          details.parent = 1;
          details.isLeaf = 0;
          details.hasChild = '1';
          _this.dataSource.push(details);
          _this.bussOutboundOrderDetailTable.expandedRowKeys.push(details.id)
          let detailList = item.bussInventoryDetailsList;
          const listMap = new Map();
          detailList.forEach(function(ite,index){
            //加载明细信息  todo 库存暂时没有宝洁的单号，宝洁供应商
            let pid = details.id;
            // console.log(this.bussOutboundOrderDetailTable.expandedRowKeys)
            // if (this.bussOutboundOrderDetailTable.expandedRowKeys.join(',').includes(pid)) {
            let mapList = listMap.get(pid);
            if (mapList == null) {
              mapList = [];
            }
            let detail1 = {};
            detail1.pid = details.id;
            detail1.inventoryId = ite.id;
            detail1.materialId = ite.materialId;
            detail1.materialCode = ite.materialCode;
            detail1.materialName = ite.materialName;
            detail1.noneSpec = ite.noneSpec;
            detail1.meUnit = ite.meUnit;
            detail1.meUnit_dictText = ite.meUnit_dictText;
            detail1.inventoryQuantity = ite.inventoryQuantity;
            detail1.availableQuantity = parseFloat(ite.inventoryQuantity) - parseFloat(ite.occupationQuantity)- parseFloat(ite.outboundQuantity);
            detail1.occupationQuantity = ite.occupationQuantity;
            detail1.outputQuantity = ite.outboundQuantity;
            // detail1.quantity = ite.quantity;
            detail1.batchNumber = ite.batch;
            detail1.materialBatchNumber = ite.materialBatchNumber;
            detail1.warehouseLocation = ite.warehouseLocation;
            detail1.warehousingId = ite.storageId;
            detail1.warehousingCode = ite.code;
            detail1.warehousingDate = ite.enterDate;
            detail1.restrictedDate = ite.restrictedDate;
            detail1.bjSupplierCode = ite.bjSupplierCode;
            detail1.bjSupplierName = ite.bjSupplier;
            detail1.bjNo = ite.bjOrder;
            detail1.supplierId = ite.supplierId;
            detail1.supplierName = ite.supplierName;
            detail1.parent = 0;
            detail1.isLeaf = 1;
            detail1.id = randomUUID();
            console.log(detail1);
            //todo 明细入库信息未附值
            mapList.push(detail1);
            listMap.set(pid, mapList);
            // }
          })
          console.log(listMap);
          let childrenMap = listMap;
          let fn = (list) => {
            if(list) {
              list.forEach(data => {
                if (data.id === details.id && _this.bussOutboundOrderDetailTable.expandedRowKeys.includes(data.id)) {
                  // data.hasChild = '1';
                  data.children = _this.getDataByResult(childrenMap.get(data.id))
                  // fn(data.children)
                }
              })
            }
          }
          fn(_this.dataSource)
          console.log(_this.dataSource)
          _this.dataSource = _this.getDataByResult(_this.dataSource);
        })
      })
    },
    filterPackageId(materialId){
      this.bussOutboundOrderInformationTable.dataSource = this.bussOutboundOrderInformationTable.dataSource.filter(function(item) {
        return item.materialId !== materialId;
      });
    },
    handleAddInformations() {
      if(!this.model.warehouseId){
        this.$message.error("请先选择仓库！")
        return;
      }
      this.$refs.selectInventory.add();
      this.$refs.selectInventory.title = "选择物料";
      this.$refs.selectInventory.disableSubmit = false;
    },
    deleteRow(row) {
      console.log(row)
      // 删除指定行
      const index = this.bussOutboundOrderInformationTable.dataSource.indexOf(row);
      if (index !== -1) {
        this.bussOutboundOrderInformationTable.dataSource.splice(index, 1);
        const col = this.dataSource.filter(item => item.materialId === row.materialId);
        if (col != null) {
          const colindex = this.dataSource.indexOf(col[0]);
          if (colindex !== -1) {
            this.dataSource.splice(colindex, 1);
          }
        }
      }
    },
    handleDeleteNode(row) {
      // 删除指定行
      for (let item of this.dataSource) {
        if (item.hasOwnProperty('children') ) {
          const index = item.children.indexOf(row);
          if (index !== -1) {
            item.children.splice(index, 1);
          }
        }
      }
      this.dataSource = [...this.dataSource]
    },
    handleAddChild(row) {
      this.detailTemp = row;
      this.bussOutboundOrderDetailTable.expandedRowKeys.push(row.id)
      console.log(row);
      //todo 入库明细弹框内容
      this.$refs.selectInbound.add();
      this.$refs.selectInbound.title = "选择入库明细";
      this.$refs.selectInbound.disableSubmit = false;
    },
    inboundOk(row){
      let _this = this;
      console.log(row);
      postAction('/org.jeecg.modules.business/bussStorage/queryDetailByIds', { ids: row }).then(res => {
        console.log(res.result)
        let erpGoodsList = res.result;
        const listMap = new Map();
        for (let item of erpGoodsList) {
          let pid = this.detailTemp.id;
          console.log(this.bussOutboundOrderDetailTable.expandedRowKeys)
          if (this.bussOutboundOrderDetailTable.expandedRowKeys.join(',').includes(pid)) {
            let mapList = listMap.get(pid);
            if (mapList == null) {
              mapList = [];
            }
            let detail = {};
            detail.pid = this.detailTemp.id;
            detail.materialId = item.materialId;
            detail.materialCode = item.materialCode;
            detail.materialName = item.materialName;
            detail.noneSpec = item.spec;
            detail.meUnit = item.unit;
            detail.inventoryQuantity = item.num;
            detail.batchNumber = item.materialCode;
            detail.materialBatchNumber = item.materialName;
            detail.warehouseLocation = item.storehouse;
            detail.warehousingCode = item.code;
            detail.warehousingDate = item.storageDate;
            detail.restrictedDate = item.expiryDate;
            detail.supplierId = item.supplierId;
            detail.supplierName = item.supplierName;
            detail.parent = 0;
            detail.isLeaf = 1;
            detail.id = randomUUID();
            console.log(detail);
            //todo 明细入库信息未附值
            mapList.push(detail);
            listMap.set(pid, mapList);
          }
        }
        console.log(listMap);
        let childrenMap = listMap;
        let fn = (list) => {
          if(list) {
            list.forEach(data => {
              if (data.id === this.detailTemp.id && this.bussOutboundOrderDetailTable.expandedRowKeys.includes(data.id)) {
                // data.hasChild = '1';
                data.children = this.getDataByResult(childrenMap.get(data.id))
                // fn(data.children)
              }
            })
          }
        }
        fn(_this.dataSource)
        console.log(_this.dataSource)
        this.dataSource = this.getDataByResult(_this.dataSource);
      })
    },
    addBefore(){
      this.bussOutboundOrderInformationTable.dataSource=[]
      // this.getSequenceNum()
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    addProc(){
      if(this.procSelectRows.length>0){
        const rows = this.procSelectRows
        //todo 通过id找对应的领料单,查询对应的库存跟明细返回

      }
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      console.log("123")
      console.log(this.dataSource)
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.bussOutboundOrderInformation.list, params, this.bussOutboundOrderInformationTable)
        getAction(this.url.childList,params).then((res)=>{
          if(res.success){
            console.log(res.result)
            this.dataSource = res.result;
            setTimeout(() => {
              console.log(this.dataSource)
              console.log("2322")
              this.dataSource.map(item => {
                console.log(item.children)
                if (item.children != null ) {
                  item.children.map(info => {
                    this.selectedRowKeys.push(info.id);
                  })
                }
              })
              const rows = this.dataSource.map(item => {
                //判断是否标记了带有子节点
                if (item.children != null ) {
                  item.children.map(info => {
                    this.selectionRows.push(info);
                  })
                }
              })
            }, 1000);
          }
        })
      }
      console.log("123")
      console.log(this.dataSource)
    },
    //校验所有一对一子表表单
    validateSubForm(allValues){
      return new Promise((resolve,reject)=>{
        Promise.all([
        ]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      console.log(allValues);
      console.log(this.bussOutboundOrderDetailTable);
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussOutboundOrderInformationList: allValues.tablesValue[0].tableData,
        outboundOrderDetailList: this.selectionRows
      }
    },
    validateError(msg){
      this.$message.error(msg)
    },
    handleExpand(expanded, record){
      // 判断是否是展开状态
      if (expanded) {
        this.bussOutboundOrderDetailTable.expandedRowKeys.push(record.id)
        if (record.children.length>0 ) {
          // console.log("123")
          // getAction(this.url.childList,params).then((res)=>{
          //   if(res.success){
          //     if(res.result.records){
          //       record.children = this.getDataByResult(res.result.records)
          this.dataSource = [...this.dataSource]
          //     }else{
          //       record.children=''
          //       record.hasChildrenField='0'
          //     }
          //   }else{
          //     this.$message.warning(res.message)
          //   }
          // })
        }
      }else{
        let keyIndex = this.bussOutboundOrderDetailTable.expandedRowKeys.indexOf(record.id)
        if(keyIndex>=0){
          this.bussOutboundOrderDetailTable.expandedRowKeys.splice(keyIndex, 1);
        }
      }
    },
    getDataByResult(result){
      if(result){
        return result.map(item=>{
          //判断是否标记了带有子节点
          if(item[this.hasChildrenField]=='1'){
            let loadChild = { id: item.id+'_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      }
    },
    onCellChange(record, dataIndex, value) {
      let _this = this;
      var max = parseFloat(record.inventoryQuantity);
      var out = 0;
      var zhanyong = 0;
      if (record.outputQuantity != null) {
        out = parseFloat(record.outputQuantity);
      }
      if (record.occupationQuantity != null) {
        zhanyong = parseFloat(record.occupationQuantity);
      }
      max = max - out - zhanyong;
      var quantity = parseFloat(value);
      console.log(max)
      console.log(quantity)
      if (quantity > max){
        record.quantity = 0
        _this.$message.error("输入的数量大于库存数量！")
        return
      }else{
        _this.$set(record, dataIndex,value)
        const listMap = new Map();
        //勾选的总数量赋值出库单信息数量
        let list = _this.selectionRows;
        list.forEach(data => {
          let mapList = listMap.get(data.materialId);
          if (mapList == null) {
            mapList = [];
          }
          let detail = {};
          if (data.quantity !== null) {
            detail.id = data.inventoryId;
            detail.quantity = data.quantity;
            mapList.push(detail);
          }
          listMap.set(data.materialId,mapList);
        })
        let infoList = _this.bussOutboundOrderInformationTable.dataSource;
        infoList.forEach(data => {
          var num = 0;
          let mapList = listMap.get(data.materialId);
          if (mapList != null) {
            mapList.forEach(detail => {
              if (detail.quantity != null) {
                num = num + parseFloat(detail.quantity);
              }
            })
          }
          data.quantity = num;
        })
        _this.bussOutboundOrderInformationTable.dataSource = infoList;
      }

    },
    onSelectChange(selectedRowKeys, selectionRows) {
      console.log("gouxuan")
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      let _this = this;
      console.log(selectedRowKeys)
      console.log(selectionRows)
      const listMap = new Map();
      //勾选的总数量赋值出库单信息数量
      let list = _this.selectionRows;
      list.forEach(data => {
        // let num = listMap.get(data.materialId)
        let mapList = listMap.get(data.materialId);
        if (mapList == null) {
          mapList = [];
        }
        let detail = {};
        if (data.quantity !== null) {
          detail.id = data.inventoryId;
          detail.quantity = data.quantity;
          mapList.push(detail);
        }
        listMap.set(data.materialId,mapList);
      })
      console.log(listMap)
      let infoList = _this.bussOutboundOrderInformationTable.dataSource;
      console.log(infoList)
      infoList.forEach(data => {
        console.log(data)
        var quantity = 0;
        let mapList = listMap.get(data.materialId);
        if (mapList != null) {
          mapList.forEach(detail => {
            if (detail.quantity != null) {
              quantity = quantity + parseFloat(detail.quantity);
            }
          })
        }
        data.quantity = quantity;
      })
      console.log(infoList)
      _this.bussOutboundOrderInformationTable.dataSource = infoList;
      console.log(_this.bussOutboundOrderInformationTable.dataSource);
    },
    getSuperFieldList(){
      let fieldList=[];
      fieldList.push({type:'string',value:'informationId',text:'出库信息ID',dictCode:''})
      fieldList.push({type:'string',value:'materialId',text:'物料ID',dictCode:''})
      fieldList.push({type:'string',value:'materialCode',text:'物料编号',dictCode:''})
      fieldList.push({type:'string',value:'materialName',text:'物料名称',dictCode:''})
      fieldList.push({type:'string',value:'noneSpec',text:'规格型号',dictCode:''})
      fieldList.push({type:'string',value:'meUnit',text:'主计量',dictCode:'ji_unit'})
      fieldList.push({type:'BigDecimal',value:'quantity',text:'数量',dictCode:''})
      fieldList.push({type:'string',value:'batchNumber',text:'批次号',dictCode:''})
      fieldList.push({type:'string',value:'materialBatchNumber',text:'物料批号',dictCode:''})
      fieldList.push({type:'string',value:'warehouseLocation',text:'库位',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'inventoryQuantity',text:'入库数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'outputQuantity',text:'已出数量',dictCode:''})
      fieldList.push({type:'string',value:'bjSupplierCode',text:'宝洁供应商编码',dictCode:''})
      fieldList.push({type:'string',value:'bjSupplierName',text:'宝洁供应商',dictCode:''})
      fieldList.push({type:'string',value:'warehousingId',text:'入库ID',dictCode:''})
      fieldList.push({type:'string',value:'warehousingCode',text:'入库单号',dictCode:''})
      fieldList.push({type:'datetime',value:'warehousingDate',text:'入库日期'})
      fieldList.push({type:'datetime',value:'restrictedDate',text:'限用日期'})
      fieldList.push({type:'string',value:'bjNo',text:'宝洁单号',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'occupationQuantity',text:'占用数量',dictCode:''})
      fieldList.push({type:'string',value:'auUnit',text:'辅助单位',dictCode:'zl_unit'})
      fieldList.push({type:'BigDecimal',value:'auQuantity',text:'辅助数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'inAuQuantity',text:'入库辅助数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'outAuQuantity',text:'已出辅助数量',dictCode:''})
      fieldList.push({type:'BigDecimal',value:'occupationAuQuantity',text:'占用辅助数量',dictCode:''})
      fieldList.push({type:'string',value:'conversionRate',text:'单位换算率',dictCode:''})
      fieldList.push({type:'string',value:'supplierId',text:'供应商',dictCode:"erp_supplier,name,id"})
      fieldList.push({type:'string',value:'productionWorkshop',text:'生产车间',dictCode:"sys_depart,depart_name,id"})
      fieldList.push({type:'string',value:'customerName',text:'客户名称',dictCode:''})
      fieldList.push({type:'Text',value:'remark',text:'备注',dictCode:''})
      fieldList.push({type:'string',value:'orderNo',text:'订单编号',dictCode:''})
      fieldList.push({type:'string',value:'pid',text:'父级节点',dictCode:''})
      this.superFieldList = fieldList
    },
    openPrintPreview() {
      if (this.model.id == null){
        if(this.bussOutboundOrderInformationTable.dataSource == null || this.bussOutboundOrderInformationTable.dataSource.length < 1){
          this.$message.error("请添加出库信息再预览")
          return
        }
      }
      console.log(store)
      var name = store.getters.userInfo.realname;
      const params = {
        templateId: '979158814296924160',
        title: '出库单',
        code: this.model.code,
        remark: this.model.remark,
        create_time: this.model.createTime,
        create_by: name,
        outbound_type: this.model.outboundType,
        warehouse_id: this.model.warehouseId,
        department_workshop: this.model.departmentWorkshop,
        now_date: estar.toDate(new Date(), "yyyy-MM-dd HH:mm:ss"),
        infos: this.bussOutboundOrderInformationTable.dataSource
      }
      var info = [];
      info.push(params)
      console.log(params);
      let token = store.getters.token
      let id = this.selectedRowKeys[0]
      console.log("预览")
      window.open(`${window._CONFIG['domianURL']}/jmreport/view/979158814296924160?token=${token}&info=${info}`, '_blank');
      // this.$router.push({path:'/business/outbound/PrintPreviewForm',query: {id:id,token:token,info: params }})
    },
  }
}
</script>

<style scoped>
</style>